#include <mvDirAndCreateMap.h>

/// 生成DB映射，从DB中获取chainID
/// void CreateDB
/// int GetChainIDFromDB


#include <iostream>
#include <sqlite3.h>
#include "io/AppConfig.h"

// #define WRL_START_CHAIN 30
int WRL_START_CHAIN;

// 插入数据的函数，每次插入一行
int insertRow(sqlite3* db, int WRLID, int PARTID,int WORKID ,int CHAIN) {
    sqlite3_stmt* stmt;
    const char* sql = "INSERT INTO Chains (WRLID, PARTID, WORKID, CHAIN) VALUES (?,?, ?, ?);";
    int rc;

    // 准备SQL语句
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) {
        std::cerr << "无法准备语句: " << sqlite3_errmsg(db) << std::endl;
        return rc;
    }

    // 绑定数据
    sqlite3_bind_int(stmt, 1, WRLID);  // 绑定 WRLID
    sqlite3_bind_int(stmt, 2, PARTID); // 绑定 PARTID
    sqlite3_bind_int(stmt, 3, WORKID);  // 绑定 CHAIN
    sqlite3_bind_int(stmt, 4, CHAIN);  // 绑定 CHAIN

    // 执行插入操作
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        std::cerr << "插入数据失败: " << sqlite3_errmsg(db) << std::endl;
    } else {
        std::cout << "成功插入数据: WRLID=" << WRLID << ", PARTID=" << PARTID << ", CHAIN=" << CHAIN << std::endl;
    }

    // 清理
    sqlite3_finalize(stmt);

    return rc;
}

int CreateDB(const WRLJsonMap& aMap)
{
    sqlite3* db;
    char* errMsg = 0;
    int rc;
    createDirectories("runDB");
    deleteFile("runDB/mids.db");
    // 打开数据库文件，如果文件不存在，则创建它
    rc = sqlite3_open("runDB/mids.db", &db);
    if (rc) {
        std::cerr << "无法打开数据库: " << sqlite3_errmsg(db) << std::endl;
        return (1);
    } else {
        std::cout << "数据库成功打开!" << std::endl;
    }

    // 创建表格（如果表格已经存在，则跳过）
    const char* createTableSQL = "CREATE TABLE IF NOT EXISTS Chains ("
                                 "ID INTEGER PRIMARY KEY AUTOINCREMENT, "
                                 "WRLID INTEGER NOT NULL, "
                                 "PARTID INTEGER NOT NULL, "
                                 "WORKID INTEGER NOT NULL, "
                                 "CHAIN INTEGER NOT NULL);";

    rc = sqlite3_exec(db, createTableSQL, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        std::cerr << "创建表格失败: " << errMsg << std::endl;
        sqlite3_free(errMsg);
    } else {
        std::cout << "表格成功创建/已存在!" << std::endl;
    }

    int startCh = WRL_START_CHAIN;
    for(auto k:aMap){
        for(int i =0;i<k.second.partCount+1;i++){
            insertRow(db, k.second.wrlid, i,k.second.workstation, startCh); // 插入一行数据
            startCh++;
        }
    }


    // 关闭数据库连接
    sqlite3_close(db);
    return 0;
}



// 查询并返回CHAIN值的函数
int getChainID(sqlite3* db, int PARTID, int WRLID) {
    sqlite3_stmt* stmt;
    const char* sql = "SELECT CHAIN FROM Chains WHERE PARTID = ? AND WRLID = ?;";  // 查询链的SQL语句
    int rc;

    // 准备SQL语句
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) {
        std::cerr << "无法准备语句: " << sqlite3_errmsg(db) << std::endl;
        return -1;  // 如果准备语句失败，返回-1
    }

    // 绑定参数
    sqlite3_bind_int(stmt, 1, PARTID);  // 绑定PARTID
    sqlite3_bind_int(stmt, 2, WRLID);   // 绑定WRLID


    // 执行查询
    rc = sqlite3_step(stmt);
    int chainID = -1;  // 默认返回 -1 表示没有找到

    if (rc == SQLITE_ROW) {
        // 如果查询到结果，获取CHAIN列的值
        chainID = sqlite3_column_int(stmt, 0);
        std::cout << "找到记录: CHAINID = " << chainID << std::endl;
    } else if (rc == SQLITE_DONE) {
        std::cout << "未找到符合条件的记录。" << std::endl;
    } else {
        std::cerr << "查询执行失败: " << sqlite3_errmsg(db) << std::endl;
    }

    // 清理
    sqlite3_finalize(stmt);

    return chainID;
}



/**
    * 将胡博的生存路径拷贝到某个地址
**/
int main(int argc, char *argv[])
{
    AppConfig config;

    from_json("conf/config.json",config);
    WRL_START_CHAIN = config.Wrl_start;

    if(argc > 1){
        clearFolderContents("TargetWRL");
        createDirectories("TargetWRL");
        std::string pathContainer = argv[1];

        std::cout << "输入WRL文件夹为:" << pathContainer << std::endl;

        WRLJsonMap aMap;

        auto lst = getSubdirectoriesPath(pathContainer);
        for(auto l_dir:lst){
            std::cout << "子文件夹为:" << l_dir << std::endl;
            WRLJson js;
            std::string Json = l_dir.string() + "/wrl.json";
            auto nl = stringToJson(Json);
            from_json(nl,js);
            js.dir_path = "TargetWRL/" + l_dir.filename().string();
            aMap[js.wrlid] = js;
        }
        CreateDB(aMap);
        saveWRLJsonMapToFile(aMap,"runDB/HuSerial.json");

        URDFLinks links;
        for(const auto &am:aMap){
            for(auto df:am.second.urdfs){
                links.push_back(am.second.dir_path + "/" + df.second);
            }
        }
        auto ret = serializeVectorToJson(links);
        WriteStr2File("TargetWRL/AllFile.json",ret);

        copyDirectoryRecursively(pathContainer,"TargetWRL");
    }else{
        std::cerr << "拷贝文件需要参数填写." << std::endl;
    }
    return 0;
}
